<?php

namespace App\Http\Controllers\Alipay;

use App\Enums\SmsTempEnum;
use App\Http\Controllers\Controller;
use App\Jobs\SendChangeOrderMessage;
use App\Jobs\SendSmsMessageJob;
use App\Models\Order;
use App\Models\OrderDepict;
use App\Models\OrderLease;
use App\Models\OrderRemark;
use App\Models\OrderGoods;
use App\Models\OrderLog;
use App\Models\OtherWithholdLog;
use App\Models\OrderInsurancePay;
use App\Models\AuthenticLog;
use App\Models\MemberOther;
use App\Services\AlipayMessageService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\OtherCallbacksService;
use App\Services\AntchainService;
use App\Services\RelationVerifyService;
use App\Services\XinyanService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class NoticeController extends Controller
{

    /**
     * 小程序预授权回调地址
     * @return void
     */
    public function preAuthNotify(Request $request)
    {
        $result = $request->all();
        Log::info('小程序预授权回调');

        if (!empty($result) && isset($result['status']) && $result['status'] == 'SUCCESS') {
            $orderNo = explode("|", $result['out_order_no']);
            $order = Order::from('sp_order_2 as o')
                ->select('o.id', 'o.mini_id', 'o.uid', 'o.other_order_id', 'o.other_user_id', 'o.rent_total',
                    'o.trade_no', 'm.mobile', 'o.realname', 'o.seller_id', 'og.goods_title',
                    'og.imgurl', 'o.pay_type', 'o.flow_id', 'o.is_skip', 'o.foregift', 'o.sale_user_id',
                    'm.cert_name', 'm.cert_no', 'm.user_id', 'og.pact_type', 'o.month_total', 'o.is_renewal', 'o.parent_order_no')
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->where(['trade_no' => $orderNo[0]])
                ->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $save = [];
                //$save['pay_type'] = 2;
                //$save['status'] = 9;
                if ($request->input('notify_type') == "fund_auth_freeze") {

                }

                $save['alipay_trade_no'] = $result['operation_id'];
                $save['rights_auth_no'] = $result['auth_no'];
                if (isset($result['pre_auth_type']) && $result['pre_auth_type'] == 'CREDIT_AUTH') {
                    $save['foregift_deduct'] = bcsub($order['foregift'], $result['total_pay_amount'], 2);
                    $save['foregift_pay'] = $result['total_pay_credit_amount'] ? $result['total_pay_credit_amount'] : $result['total_pay_amount'];
                } else {
                    $save['foregift_deduct'] = bcsub($order['foregift'], $result['total_freeze_amount'], 2);
                    $save['foregift_pay'] = $result['total_freeze_amount'];
                }
                Order::where(['id' => $order['id']])->update($save);

                $save['order_id'] = $order['id'];
                $save['cert_name'] = $order['cert_name'];
                $save['cert_no'] = $order['cert_no'];
                $save['mobile'] = $order['mobile'];
                $save['uid'] = $order['uid'];
                AlipayService::alipayCreditPreQuery($order['mini_id'], $save);

                if ($order && $order['seller_id'] != '202309081070080001' && $order['sale_user_id'] != '022215565466') {
                    $order['order_id'] = $order['id'];
                    $RelationVerifyService = new RelationVerifyService();
                    $RelationVerifyService->lawSuitPersonal($order);
                }

                //
                Order::where(['id' => $order['id']])->where('status', 3)->update([
                    'pay_type' => 2,
                    'status' => 10,
                ]);

                echo "success";
                exit;
            }
        }
        echo "fail";
        exit;


    }

    /**
     * 扣除押金异步回调
     */
    public function deductDepositNotify(Request $request)
    {
        $request_data = $request->all();
        Log::info('扣除押金异步回调');

        if (!empty($request_data) && isset($request_data['trade_status']) && $request_data['trade_status'] == 'TRADE_SUCCESS') {
            $order_lease_arr = explode("|", $request_data['out_trade_no']);
            $trade_no = $order_lease_arr[0];
            $order_lease_id = $order_lease_arr[1];
            $order = Order::from('sp_order_2 as o')->where('o.trade_no', $trade_no)
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->select('o.id', 'o.uid', 'o.seller_id', 'o.realname', 'o.trade_no', 'o.mobile', 'o.other_order_id', 'o.other_user_id', 'o.rent_total', 'og.goods_title', 'og.imgurl', 'm.user_id', 'o.is_skip', 'm.cert_name', 'm.cert_no', 'm.mobile', 'og.pact_type', 'o.month_total', 'o.is_renewal', 'o.parent_order_no')->first();
            $order = $order ? $order->toArray() : [];
            if (!empty($order)) {
                $withholdLog = OtherWithholdLog::where([['out_trade_no', $request_data['out_trade_no']], ['order_no', $trade_no], ['status', OtherWithholdLog::STATUS_FAIL], ['pay_type', OtherWithholdLog::PAY_TYPE_DEPOSIT]])->select('id', 'order_no')->first();
                $withholdLog = obToArray($withholdLog);
                if (!empty($withholdLog)) {
                    DB::beginTransaction();
                    $log_save['trade_no'] = $request_data['trade_no'];
                    $log_save['status'] = OtherWithholdLog::STATUS_SUCCESS;
                    $log_save['result'] = json_encode($request_data);
                    $logRes = OtherWithholdLog::where('id', $withholdLog['id'])->update($log_save);

                    $data['order_id'] = $order['id'];
                    $data['which_period'] = $order['month_total'] + 1;
                    $data['begin_time'] = strtotime(date('Y-m-d', strtotime($order['end_time'])));
                    $data['end_time'] = $data['begin_time'] + 24 * 3600;
                    $data['rent'] = $request_data['receipt_amount'];
                    $data['create_time'] = strtotime($request_data['gmt_payment']);
                    $data['paid_rent'] = $request_data['receipt_amount'];
                    $data['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;
                    $data['pay_time'] = strtotime($request_data['gmt_payment']);
                    $data['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                    $data['alipay_trade_no'] = $request_data['trade_no'];
                    $data['trade_no'] = $request_data['trade_no'];
                    $addRes = OrderLease::insert($data);

                    if ($logRes && $addRes) {
                        DB::commit();
                        OtherWithholdLog::orderWithholdLog($order['trade_no'], 0, $request_data['out_trade_no'], $request_data['trade_no'], $request_data, OtherWithholdLog::PAY_TYPE_DEPOSIT, true, 1);
                        echo "success";
                        exit;
                    } else {
                        DB::rollBack();
                        echo "fail1";//数据更新失败
                        exit;
                    }
                } else {
                    echo "fail1";//数据更新失败
                    exit;
                }
            } else {
                echo "fail1";//数据更新失败
                exit;
            }
        }
    }


    /**
     * 主动支付回调
     * @param Request $request
     * @throws \Exception
     */
    public function prepaymentNotify(Request $request)
    {
        $result = $request->all();
        Log::info('主动支付回调');
        AlipayService::requestLog('主动支付回调', $result);


        if (!empty($result) && isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
            $orderNo = explode("|", $result['out_trade_no']);
            $order = Order::from('sp_order_2 as o')->select('o.id', 'o.uid', 'o.other_order_id', 'o.other_user_id', 'o.rent_total',
                'o.trade_no', 'o.mobile', 'o.realname', 'o.seller_id', 'og.goods_title', 'og.imgurl', 'o.sign_no','o.is_insurance_choose','o.is_insurance_choose_custom',
                'o.pay_type', 'o.flow_id', 'o.is_skip', 'm.cert_name', 'm.cert_no', 'm.user_id', 'og.pact_type', 'o.month_total','o.is_renewal', 'o.parent_order_no')
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->where(['trade_no' => $orderNo[0]])
                ->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $passback_params = urldecode($result['passback_params']);
                $leaseID = explode(",", $passback_params);

                $leaseSave['alipay_trade_no'] = $result['trade_no'];
                $leaseSave['trade_no'] = $result['trade_no'];
                $leaseSave['out_order_no'] = $result['out_trade_no'];
                $leaseSave['pay_time'] = strtotime($result['gmt_payment']);
                $leaseSave['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;

                //更改已还租期
                Order::where(['id' => $order['id']])->increment('month_paid', count($leaseID));

                $orderLease = OrderLease::whereIn('id', $leaseID)->select('id', 'which_period', 'rent', 'paid_rent')->get();
                $orderLease = obToArray($orderLease);
                $leaseTotal = [];
                $zlbLeaseId = [];
                foreach ($orderLease as $lease) {
                    //更新账单数据
                    OrderLease::where('id', $lease['id'])->update($leaseSave);
                    if ($lease['which_period'] == 1) {
                        $is_insurance_choose_custom=GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']);
                        if($is_insurance_choose_custom<=0){
                            $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                        }
                        $arr['pay_time'] = strtotime($result['gmt_payment']);
                        Order::where(['id' => $order['id']])->update($arr);
                        SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::KX_SHOPPING);
                        AntchainAtoService::repayWithholdPlan($order['trade_no'], 1, $lease['rent']);

                    }

                    if ($order['sign_no']) { //蚂蚁链租赁平台智能合同代扣 主动支付后取消改期代扣规则
                        AntchainAtoService::repayWithholdPlan($order['trade_no'], $lease['which_period'], $lease['rent']);
                    }

                    $coupon = bcsub($result['total_amount'], $result['receipt_amount'], 2);
                    //查询是否有待履约的芝麻信用记录
                    OtherWithholdLog::orderWithholdLog($order['trade_no'], $lease['id'], $result['out_trade_no'], $result['trade_no'], $result, OtherWithholdLog::PAY_TYPE_PREPAYMENT, true, 1, 0, $coupon);
                    $leaseTotal[$lease['id']] = bcsub($lease['rent'], $lease['paid_rent'], 2);
                }
                //更新实付款金额
                if ($leaseTotal = computeDiscount($leaseTotal, $result['total_amount'])) {
                    foreach ($leaseTotal as $k => $value) {
                        //更新账单数据-商家实际收金额
                        OrderLease::where(["id" => $k])->increment('paid_rent', $value);
                    }
                }
                //检测逾期订单状态
                if ($status = Order::checkOrderOverdueStatus($order['id'])) {
                    Order::where(['id' => $order['id']])->update(['status' => $status, 'pay_time' => time()]);
                }

                //订单中心
                SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::CONSUMER,'PAYMENT_S');
                SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::CONSUMER,'PAID_OFF');


                echo "success";
                exit;
            }
        }
        echo "fail";
        exit;

    }


    /**
     * 买断支付回调
     * @param Request $request
     * @throws \Exception
     */
    public function orderBuyoutNotify(Request $request)
    {
        $result = $request->all();
        Log::info("买断支付回调");

        if ($result['trade_status'] == 'TRADE_SUCCESS') {
            $orderNo = explode("|", $result['out_trade_no']);
            $order = Order::from('sp_order_2 as o')
                ->select('o.id', 'o.uid', 'o.mini_id', 'o.other_order_id', 'o.other_user_id', 'o.rent_total',
                    'o.trade_no', 'o.mobile', 'o.realname', 'o.seller_id', 'og.goods_title', 'og.imgurl', 'o.month_total',
                    'o.end_time', 'o.alipay_trade_no', 'o.rights_auth_no', 'o.pay_type', 'o.flow_id')
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->where(['trade_no' => $orderNo[0]])
                ->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $miniId = $order['mini_id'];

                $leaseSave['alipay_trade_no'] = $result['trade_no'];
                $leaseSave['trade_no'] = $result['trade_no'];
                $leaseSave['out_order_no'] = $result['out_trade_no'];
                $leaseSave['pay_time'] = strtotime($result['gmt_payment']);
                $leaseSave['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;

                $orderLease = OrderLease::where([['order_id', $order['id']], ['status', '!=', OrderLease::ORDER_LEASE_STATUS_PAID]])->select('id', 'which_period', 'rent')->get();
                $orderLease = obToArray($orderLease);
                $buyout_total_rent = sprintf("%.2f", array_sum(array_column($orderLease, 'rent')));
                $receipt_amount = $result['receipt_amount'];
                $zlbLeaseId = [];
                if (!empty($orderLease)) {
                    if ($receipt_amount < $buyout_total_rent) {
                        foreach ($orderLease as $lease) {
                            $zlbLeaseId[] = $lease['id'];
                            if ($receipt_amount > 0) {
                                if ($receipt_amount > $lease['rent']) {
                                    $leaseSave['paid_rent'] = $lease['rent'];
                                    $receipt_amount = $receipt_amount - $lease['rent'];
                                } else {
                                    $leaseSave['paid_rent'] = $receipt_amount;
                                    $receipt_amount = 0;
                                }
                                //更新账单数据
                                OrderLease::where(["id" => $lease['id']])->update($leaseSave);
                            }
                            //查询是否有待履约的芝麻信用记录
                            OtherWithholdLog::orderWithholdLog($order['trade_no'], $lease['id'], $result['out_trade_no'], $result['trade_no'], $result, OtherWithholdLog::PAY_TYPE_PREPAYMENT, true, $order['uid']);
                        }
                    } else {
                        foreach ($orderLease as $lease) {
                            $zlbLeaseId[] = $lease['id'];
                            $leaseSave['paid_rent'] = $lease['rent'];
                            //更新账单数据
                            OrderLease::where(["id" => $lease['id']])->update($leaseSave);
                            //查询是否有待履约的芝麻信用记录
                            OtherWithholdLog::orderWithholdLog($order['trade_no'], $lease['id'], $result['out_trade_no'], $result['trade_no'], $result, OtherWithholdLog::PAY_TYPE_PREPAYMENT, true, $order['uid']);
                        }
                    }
                }
                $buyout = sprintf("%.2f", $result['receipt_amount'] - $buyout_total_rent);
                if ($buyout > 0) {
                    $data['order_id'] = $order['id'];
                    $data['which_period'] = $order['month_total'] + 1;
                    $data['begin_time'] = strtotime(date('Y-m-d', strtotime($order['end_time'])));
                    $data['end_time'] = $data['begin_time'] + 24 * 3600;
                    $data['rent'] = $buyout;
                    $data['create_time'] = strtotime($result['gmt_payment']);
                    $data['paid_rent'] = $buyout;
                    $data['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;
                    $data['pay_time'] = strtotime($result['gmt_payment']);
                    $data['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                    $data['alipay_trade_no'] = $result['trade_no'];
                    $data['trade_no'] = $result['trade_no'];
                    OrderLease::insert($data);
                }
                //更改已还租期和订单状态
                Order::where(['id' => $order['id']])->update(['month_paid' => $order['month_total'], 'status' => OrderService::ORDER_STATUS_BUYOUT_PAY]);

                if ($order['pay_type'] == Order::ORDER_PAY_TYPE_ZM) { //买断完成解约预授权
                    $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                    $alipay_data['authNo'] = $order['rights_auth_no'];
                    $prequery = AlipayService::alipayPreQuery($order['mini_id'], $alipay_data);
                    if ($prequery['status']) {
                        $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                        if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                            $thaw_data['amount'] = $rest_amount;
                            $thaw_data['authNo'] = $order['rights_auth_no'];
                            $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                            if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                                //查找扣款失败未履约的订单
                                $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                                    ->groupBy('out_trade_no')
                                    ->get();
                                foreach ($log as $value) {
                                    $orderData = [
                                        'orderId' => $value['order_no'],
                                        'outTradeNo' => $value['out_trade_no'],
                                        'tradeNo' => $value['trade_no'],
                                        'status' => 'CLOSED',
                                    ];
                                    AlipayService::orderInfo($miniId, $orderData);
                                }
                            }
                        }
                    }
                } else if ($order['pay_type'] == Order::ORDER_PAY_TYPE_ANTCHAIN) {//智能合同代扣订单，买断支付完成取消智能合同剩余代扣条目
                    AntchainService::paytradeCancel($order['flow_id']);
                }
                //账单付款分佣
                OtherCallbacksService::payRentalLeaseNotify($order['id'], implode(",", $zlbLeaseId));
                OrderLog::addOrderLog($order['id'], $order['uid'], OrderLog::ORDER_LOG_OPERATE_TYPE_USER, '用户买断完成');
                echo "success";
                exit;
            } else {
                echo "fail";
                exit;
            }
        } else {
            echo "fail";
            exit;
        }
    }



    /**
     * 碎屏险购买支付回调
     * @param Request $request
     * @throws \Exception
     */
    public function orderInsuranceNotify(Request $request)
    {
        $result = $request->all();
        Log::info('碎屏险购买支付回调');

        if (!empty($result) && isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
            $passback_params = urldecode($result['passback_params']);
            $rechargeLog = obToArray(OrderInsurancePay::where(['order_id' => $passback_params, 'out_trade_no' => $result['out_trade_no']])->first());
            if ($rechargeLog) {
                $data['trade_no'] = $result['trade_no'];
                $data['status'] = OrderInsurancePay::STATUS_SUCCESS;
                $data['result'] = json_encode($result);
                $data['amount'] = $result['receipt_amount'];
                OrderInsurancePay::where('id', $rechargeLog['id'])->update($data);

                Order::where('id', $rechargeLog['order_id'])->update(['is_insurance_buy' => OrderInsurancePay::STATUS_SUCCESS, 'status' => OrderService::ORDER_STATUS_SIGN_NOCHECK]);

                echo "success";
                exit;
            }
        }
        echo "fail";
        exit;
    }


    /**
     * e签宝人脸识别回调
     */
    public function faceAuthNotice(Request $request)
    {
        $request_data = $request->all();
        EsignService::addLog('e签宝人脸识别回调','',$request_data);

        $flow_id = $request_data['flowId'];
        $status = $request_data['status'];
        $contextId = $request_data['contextId'];
        if ($status) {
            $log = AuthenticLog::where(['certify_id' => $flow_id])->orderBy('id', 'desc')->select('id', 'uid','order_id', 'cert_no', 'cert_name', 'idcard_front', 'idcard_back')->first();
            $log = obToArray($log);

            if ($log) {
                $update = [];
                $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;
                $update['result'] = json_encode($request_data);
                AuthenticLog::where(['id' => $log['id']])->update($update);


                MemberOther::where(['id' => $log['uid']])->update(['idcard_front' => $log['idcard_front'],
                    'certify_id' =>$flow_id,
                    'idcard_back' => $log['idcard_back'], 'cert_name' => $log['cert_name'],
                    'cert_no' => $log['cert_no']]);
                if(Redis::get('esign_create_file_template'.$log['uid'])){
                    return true;
                }
                Redis::setEx('esign_create_file_template'.$log['uid'], 72000, 1);

                $member=MemberOther::query()->where('id',$log['uid'])->select('id as uid','mobile', 'cert_no', 'cert_name')->first();
                XinyanService::fsUserData($member);



//                $user =MemberOther::query()
//                    ->select('id','cert_name','cert_no','mobile')
//                    ->first();
//                RiskService::licenseUrl($log['order_id']);
//                $RelationVerifyService=new RelationVerifyService();
//                $RelationVerifyService->lawSuitPersonal($user);
//                OrderService::createTwo($order);
//                OrderService::createTwoOne($order);

            }
        }

        return $request_data;
    }

    /**
     * e签宝人脸识别回调-签署合同
     */
    public function faceAuthSignNotice(Request $request)
    {
        $request_data = $request->all();
        Log::info('e签宝人脸识别回调-签署合同');
        AlipayService::requestLog('蚂蚁链租赁平台回调', $request_data);



        $flow_id = $request_data['flowId'];
        $status = $request_data['status'];
        $contextId = $request_data['contextId'];
        if ($status) {
            $log = AuthenticLog::where(['certify_id' => $flow_id])->select('id', 'order_id', 'cert_no', 'cert_name', 'idcard_front', 'idcard_back')->first();
            $log = obToArray($log);
            if ($log) {
                $update = [];
                $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;
                $update['result'] = json_encode($request_data);
                AuthenticLog::where(['id' => $log['id']])->update($update);
                $order_data = Order::where('id', $log['order_id'])->select('uid')->first();
                //更新数据
                MemberOther::where(['id' => $order_data['uid']])->update(['idcard_front' => $log['idcard_front'], 'idcard_back' => $log['idcard_back'], 'cert_name' => $log['cert_name'], 'cert_no' => $log['cert_no']]);
            }
        }
        return $request_data;
    }


    /**
     * 租赁平台回调
     */
    public function antchainAtoNotify(Request $request)
    {

        $request_data = $request->all();
        Log::info('蚂蚁链租赁平台回调');
        AlipayService::requestLog('蚂蚁链租赁平台回调', $request_data);

        if ($request_data['msg_type'] == 'WITHHOLD_SIGN_STATUS_CHANGE') {//代扣签约状态变化
            $orderId = $request_data['order_id'];
            $order = Order::where('trade_no', $orderId)->select('id', 'status', 'month_total', 'sign_no','prepayment_total','is_insurance_choose_custom')->first();
            $order = obToArray($order);
            if (!empty($order)) {
                if ($request_data['status'] == 'SIGNED') {
                    $res = Order::where('trade_no', $orderId)->update(['withhold_status' => 1]);
                    if ($res) {
                        SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::KX_SHOPPING);
                        if ($order['sign_no']) { //蚂蚁链租赁平台智能合同代扣 主动支付后取消改期代扣规则
                            //取消第一期代扣
                            SendSmsMessageJob::dispatch(SmsTempEnum::PENDING_PAYMENT,$order['id'])->delay(60*30);
                            SendSmsMessageJob::dispatch(SmsTempEnum::PENDING_PAYMENT,$order['id'])->delay(86400);
                            SendSmsMessageJob::dispatch(SmsTempEnum::PENDING_PAYMENT,$order['id'])->delay(86400*3);

                        }
                        echo "success";
                    }
                    exit;
                }
            } else {
                echo "fail";//数据更新失败
                exit;
            }
        } elseif ($request_data['msg_type'] == 'USER_FULFILLMENT_LOG' && $request_data['rental_return_state'] == 'RETURN_FULL' && $request_data['return_way'] == 'ANTDIGITAL') {//租赁宝代扣执行成功通知
            $orderId = $request_data['order_id'];
            $which_period = $request_data['lease_term_index'];
            $order = Order::from('sp_order_2 as o')->where('o.trade_no', $orderId)
                ->leftjoin('sp_shop_user_2 as u', 'u.member_id', 'o.seller_id')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->select(
                    'o.id', 'o.uid', 'o.status', 'o.rent_total', 'o.month_total', 'o.foregift', 'o.seller_id', 'o.trade_no',
                    'o.realname', 'o.flow_id', 'o.amount', 'o.other_order_id', 'o.other_user_id', 'o.form_id', 'o.create_time',
                    'o.payer_user_id', 'o.order_from', 'o.is_skip', 'o.financing_type', 'o.begin_time', 'o.end_time', 'o.pay_type'
                    , 'og.goods_title', 'og.lease_price', 'og.lease_set', 'og.goods_id', 'og.setmeal_id', 'og.spec_id',
                    'og.lease_time', 'og.start_date', 'og.imgurl', 'og.setmeal_foregift', 'og.setmeal_price','o.is_insurance_choose',
                    'o.is_insurance_choose_custom'
                    , 'u.shopname', 'u.is_guarantee', 'u.guarantee_amount', 'u.guarantee_minage', 'u.guarantee_maxage'
                    , 'm.user_id', 'm.cert_no', 'm.cert_name', 'm.mobile'
                )
                ->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $order_lease = OrderLease::where([['order_id', $order['id']], ['which_period', $which_period]])->select('id', 'which_period',
                    'begin_time', 'rent', 'status')->first();
                $order_lease = obToArray($order_lease);
                if (!empty($order_lease)) {
                    if ($order_lease['status'] == OrderLease::ORDER_LEASE_STATUS_NOPAY || $order_lease['status'] == OrderLease::ORDER_LEASE_STATUS_OVERDUE) {
                        if ($order_lease['which_period'] == 1) {

                            $is_insurance_choose_custom=GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']);
                            if($is_insurance_choose_custom<=0){
                                $order_arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                                Order::where(['id' => $order['id']])->update($order_arr);
                            }
                        }

                        if ($order_lease['which_period'] == 1) {
                            SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::KX_SHOPPING);
                        }


                        if (OrderLease::where([['order_id', $order['id']], ['status', OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']) {
                            Order::where(['id' => $order['id']])->update(['status' => OrderService::ORDER_STATUS_TOBE_RETURNED]);
                        }

                        DB::beginTransaction();
                        $lease_data['paid_rent'] = $request_data['rental_money'] / 100;
                        $lease_data['alipay_trade_no'] = $request_data['return_voucher_serial'];
                        $lease_data['trade_no'] = $request_data['return_voucher_serial'];
                        $lease_data['out_order_no'] = $request_data['return_voucher_serial'] . '_' . $request_data['lease_term_index'];
                        $lease_data['pay_time'] = time();
                        $lease_data['pay_type'] = OrderLease::LEASE_PAY_TYPE_ANTCHAIN;
                        $lease_data['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $lease_res = OrderLease::where('id', $order_lease['id'])->update($lease_data);
                        //添加代扣记录表数据
                        $withhold_data['order_no'] = $order['trade_no'];
                        $withhold_data['lease_id'] = $order_lease['id'];
                        $withhold_data['out_trade_no'] = $request_data['return_voucher_serial'] . '_' . $request_data['lease_term_index'];
                        $withhold_data['trade_no'] = $request_data['return_voucher_serial'];
                        $withhold_data['result'] = json_encode($request_data);
                        $withhold_data['status'] = OtherWithholdLog::STATUS_SUCCESS;
                        $withhold_data['pay_type'] = OtherWithholdLog::PAY_TYPE_ANTCHAIN;
                        $withhold_data['create_time'] = date('Y-m-d H:i:s');
                        $withhold_add = OtherWithholdLog::insert($withhold_data);
                        if ($lease_res && $withhold_add) {
                            DB::commit();
                            //检测逾期订单状态
                            $status = Order::checkOrderOverdueStatus($order['id']);
                            if ($status) {
                                Order::where(['id' => $order['id']])->update(['status' => $status]);
                            }
                            SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::CONSUMER,'PAYMENT_S');
                            SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::CONSUMER,'PAID_OFF');

                            echo "success";//数据更新失败
                            exit;
                        } else {
                            DB::rollBack();
                            echo "fail";//数据更新失败
                            exit;
                        }
                    } else {
                        echo "success";//数据更新失败
                        exit;
                    }
                } else {
                    echo "fail";//数据更新失败
                    exit;
                }
            } else {
                echo "fail";//数据更新失败
                exit;
            }
            //租赁宝代扣失败通知
        } elseif ($request_data['msg_type'] == 'USER_FULFILLMENT_LOG' && $request_data['rental_return_state'] == 'NOT_RETURN' && $request_data['return_way'] == 'ANTDIGITAL') {
            $orderId = $request_data['order_id'];

            $which_period = $request_data['lease_term_index'];
            $order = Order::from('sp_order_2 as o')->where('o.trade_no', $orderId)
                ->leftjoin('sp_shop_user_2 as u', 'u.member_id', 'o.seller_id')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->select(
                    'o.id', 'o.uid', 'o.status', 'o.rent_total', 'o.month_total', 'o.foregift', 'o.seller_id', 'o.trade_no', 'o.realname', 'o.flow_id', 'o.amount', 'o.other_order_id', 'o.other_user_id', 'o.form_id', 'o.create_time', 'o.payer_user_id', 'o.order_from', 'o.is_skip', 'o.financing_type', 'o.begin_time', 'o.end_time', 'o.pay_type'
                    , 'og.goods_title', 'og.lease_price', 'og.lease_set', 'og.goods_id', 'og.setmeal_id', 'og.spec_id', 'og.lease_time', 'og.start_date', 'og.imgurl', 'og.setmeal_foregift', 'og.setmeal_price'
                    , 'u.shopname', 'u.is_guarantee', 'u.guarantee_amount', 'u.guarantee_minage', 'u.guarantee_maxage'
                    , 'm.user_id', 'm.cert_no', 'm.cert_name', 'm.mobile'
                )
                ->first();
            $order = obToArray($order);

            if (!empty($order)) {
                $order_lease = OrderLease::where([['order_id', $order['id']], ['which_period', $which_period]])->select('id', 'which_period', 'begin_time', 'status')->first();
                $order_lease = obToArray($order_lease);

                if (!empty($order_lease)) {
                    if ($order_lease['status'] == OrderLease::ORDER_LEASE_STATUS_NOPAY || $order_lease['status'] == OrderLease::ORDER_LEASE_STATUS_OVERDUE) {
                        $create_time = date('Y-m-d H:i:s', time() - 1800);
                        SendChangeOrderMessage::dispatch($order['id'],AlipayMessageService::CONSUMER,'PAYMENT_F');

                        if (OtherWithholdLog::where([['order_no', $order['trade_no']], ['lease_id', $order_lease['id']], ['create_time', '>', $create_time]])->count() == 0) {
                            //添加代扣记录表数据
                            $withhold_data['order_no'] = $order['trade_no'];
                            $withhold_data['lease_id'] = $order_lease['id'];
                            $withhold_data['out_trade_no'] = $request_data['trace_id'];
                            $withhold_data['result'] = json_encode($request_data);
                            $withhold_data['status'] = OtherWithholdLog::STATUS_FAIL;
                            $withhold_data['pay_type'] = OtherWithholdLog::PAY_TYPE_ANTCHAIN;
                            $withhold_data['create_time'] = date('Y-m-d H:i:s');
                            $withhold_add = OtherWithholdLog::insert($withhold_data);
                            if ($withhold_add) {
                                return DockingReturnMsg(CommonService::HTTP_ANTCHAIN_CODE_SUCCESS, '成功');
                            } else {
                                return DockingReturnMsg(CommonService::HTTP_CODE_FAIL, '失败');
                            }
                        } else {
                            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL, '代扣记录已添加');
                        }
                    } else {
                        return DockingReturnMsg(CommonService::HTTP_CODE_FAIL, '失败');
                    }
                } else {
                    return DockingReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
                }
            } else {
                return DockingReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        } elseif ($request_data['msg_type'] == 'ASYNC_UNSIGN_APPLY') {//用户解约智能合同代扣协议成功通知
            $orderId = $request_data['order_id'];
            $order = Order::query()
                ->from('sp_order_2 as o')
                ->where('o.trade_no',$orderId)
                ->leftJoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->select('o.trade_no','o.mobile','o.status','og.goods_title','o.create_time','o.id')
                ->first();
            $order = obToArray($order);
            if(!empty($order)){
                $add_remark_data = [
                    'uid'=>'23',
                    'username'=>'租赁宝',
                    'create_time'=>time(),
                    'remark'=>'(申请取消代扣协议)',
                    'order_id'=>$order['id']
                ];
                OrderRemark::insert($add_remark_data);

                if($order['status']=='39'||$order['status']=='38'){
                    $user_owe_money=OrderLease::query()->where('order_id',$order['id'])->where('status',4)->sum('rent');
                    $one= AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "REFUSE", null, bcmul($user_owe_money, 100), 'USER_OWE_MONEY');
                }else if($order['status']=='60'||$order['status']=='1'||$order['status']=='16'){
                    AntchainAtoService::cancelWithholdPlan($order['trade_no']);
                    AntchainAtoService::closeOrder($order['trade_no']);
                    $one= AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "AGREE", null, 0, null);
                }else{
                    $year=date('Y年',$order['create_time']);
                    $reason=$year.$order['goods_title'].'订单';
                    $one= AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "REFUSE", $reason, 0, 'USER_IN_SERVICE');
                }
                $one['status']=OrderService::getOrderStatusName($order['status']);
                $one['trade_no']=$order['trade_no'];
                $one['date']=date('Y-m-d H:i:s',$order['create_time']);
                $one['mobile']=$order['mobile'];
                \Illuminate\Support\Facades\Log::channel("otherlog")->debug('处理代扣协议',$one);

            }else{
                return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
            }
        }

    }

    /**
     * 订单押金回调
     * @param Request $request
     * @return void
     */

    public function orderDepictNotify(Request $request)
    {
        $result = $request->all();
        AlipayService::requestLog('支付押金回调', '', $result);
        if (!empty($result) && isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
            if($result['refund_fee']||$result['out_biz_no']){
                echo "success";
                exit;
            }
            $orderNo = $result['out_trade_no'];
            $OrderDepict = OrderDepict::where(['out_trade_no' => $orderNo])->first();
            $OrderDepict = obToArray($OrderDepict);
            if (!empty($OrderDepict)) {
                $Depict['alipay_trade_no'] = $result['trade_no'];
                $Depict['pay_time'] = date('Y-m-d H:i:s',strtotime($result['gmt_payment']));
                $Depict['pay_amount'] = $result['receipt_amount'];
                $Depict['status'] = 1;
                $Depict['pay_type'] = 1;


                //第一期租金提交
                $rent = OrderLease::where(['order_id' => $OrderDepict['order_id']])->where('which_period',1)->where('status','<>',1)->value('rent');

                if(!$rent){
                    $Depict['rent_first_amount'] = 0;
                }

                OrderDepict::where(['out_trade_no' => $orderNo])->update($Depict);
                OrderGoods::query()->where(['order_id' => $OrderDepict['order_id']])->update(['pay_cash_pledge' => 1]);

                if($rent){
                    $leaseSave['alipay_trade_no']  = $result['trade_no'];
                    $leaseSave['trade_no']     = $result['trade_no'];
                    $leaseSave['out_order_no'] = $result['out_trade_no'];
                    $leaseSave['pay_time']  = strtotime($result['gmt_payment']);
                    $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                    $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;
                    $leaseSave['paid_rent'] = $OrderDepict['rent_first_amount'];

                    //更改已还租期
                    Order::where(['id' => $OrderDepict['order_id']])->increment('month_paid',1);
                    $lease=OrderLease::where(['order_id' => $OrderDepict['order_id']])->where('which_period',1)->select('id')->first();
                    OrderLease::query()->where('id',$lease['id'])->update($leaseSave);
                    Order::where(['id' => $OrderDepict['order_id']])->update(['status'=>OrderService::ORDER_STATUS_PAY_SUCCESS,'pay_time'=>time()]);

                    $orderMain=Order::query()->where('id',$OrderDepict['order_id'])->select('trade_no','mobile','id')->first();



                    AntchainAtoService::repayWithholdPlan($orderMain['trade_no'], 1, $rent);

                    SendChangeOrderMessage::dispatch($orderMain['id'],AlipayMessageService::KX_SHOPPING);
                    SendSmsMessageJob::dispatch(SmsTempEnum::BEFORE_SHIPMENT_REMINDER,$orderMain['id'])->delay(180);

                    OtherWithholdLog::orderWithholdLog($OrderDepict['trade_no'],$lease['id'],
                        $result['out_trade_no'],$result['trade_no'],$result,OtherWithholdLog::PAY_TYPE_PREPAYMENT,true,1,);
                    //订单中心
                }else{
                    Order::where(['id' => $OrderDepict['order_id']])->update(['status'=>OrderService::ORDER_STATUS_PAY_SUCCESS,'pay_time'=>time()]);
                    //订单中心
                }

                $begin_time=OrderLease::where(['order_id' => $OrderDepict['order_id']])->where('which_period',1)->value('begin_time');

                $addTime=time()-$begin_time;
                $status=Order::query()->where(['id' => $OrderDepict['order_id']])->value('status');
                if($addTime>0&&$status<=10&&$OrderDepict['order_id']&&$begin_time){
                    DB::beginTransaction();
                    OrderLease::query()->where('order_id',$OrderDepict['order_id'])->increment('begin_time',$addTime);
                    OrderLease::query()->where('order_id',$OrderDepict['order_id'])->increment('end_time',$addTime);
                    Db::commit();
                    Log::channel('otherlog')->info('订单时间增加',['addTime'=>$addTime,'order_id'=>$OrderDepict['order_id']]);
                }



                echo "success";
                exit;
            }
        }
        echo "fail";
        exit;
    }
    /**
     * 支付券回调
     * @param Request $request
     * @throws \Exception
     */
    public function marketingActivity(Request $request)
    {
        Log::info('支付券回调');

    }

    public function alipayFromNotify(Request $request)
    {
        $result = $request->all();
        AlipayService::requestLog('支付宝From消息回调', '', $result);
    }
}
